<template>
	<view class="body">
		<myHead :title="title" />
		<uni-popup ref="popup1" type="center">
			<uni-forms-item label="文件名称" name="age">
				<input type="text" v-model="file.fileName" placeholder="请输入文件名称" />
			</uni-forms-item>
			<button type="default" class="add" @click="commit_add()"
				v-if="currentRoleCode.includes('jj-group-leader') || currentRoleCode.includes('jj-group-member')">新增</button>
		</uni-popup>
		<uni-nav-bar>
			<view slot="default">
				<uni-easyinput prefixIcon="search" v-model="fileName" placeholder="请输入内容" @iconClick="onClick" autoHeigh
					@confirm="confirm">
				</uni-easyinput>
			</view>
			<view slot="left" class="right" @click="his_back()">
				<image src="../../static/party_building/assets/files/back.png" mode=""></image>
			</view>
			<view slot="right" class="right"
				v-if="currentRoleCode.includes('jj-group-leader') || currentRoleCode.includes('jj-group-member')">
				<image @click="$refs.popup.open('top')" src="../../static/party_building/assets/files/create.png"
					mode="" class="add_dir" :style="'z-index: 9;'"></image>
				<!-- 图片上传 -->
				<uni-file-picker v-model="imageValue" style="
					position: absolute;
					opacity: 0;
					z-index: 1;
					top: 1%;" limit="1" :auto-upload="true" mode="list" file-mediatype="all" @select="select">
				</uni-file-picker>
				<image src="../../static/party_building/assets/files/upload.png" mode=""></image>
			</view>
		</uni-nav-bar>
		<!-- 弹出层 -->
		<uni-popup ref="popup" type="center" background-color="#fff">
			<uni-forms-item label="目录名称" name="age">
				<input type="text" v-model="dir_name" placeholder="请输入目录名称" />
			</uni-forms-item>
			<button type="default" class="add" @click="dir_add()">新增</button>
		</uni-popup>
		<!-- 按组使用 -->
		<scroll-view scroll-y="true" class="scroll-Y" :style="'height:'+height+'px'">
			<uni-swipe-action>
				<uni-swipe-action-item class="d_img" :threshold="20" v-for="(item,key) in directory"
					:right-options="options">
					<view @click="bindClick(item.id)">
						<image src="../../static/party_building/assets/files/directory.png" mode=""></image>
						<span class="front">{{item.path}}</span>
					</view>
					<span class="time">{{item.createTime}}</span>
					<template v-slot:right>
						<view>
							<image src="../../static/party_building/assets/files/delete.png"
								@click="deleteFile(item.id)" class="delete" mode="">
							</image>
						</view>
					</template>
				</uni-swipe-action-item>
				<!-- 文件 -->
				<uni-swipe-action-item class="d_img" :threshold="20" v-for="(item,key) in files">
					<!--   <a :hrf="item.url" :download="item.url"> -->
					<view @click="playpapers(item.url)">
						<image src="../../static/party_building/assets/files/files.png" mode=""></image>
						<span class="front">{{item.fileName}}</span>
					</view>
					<span class="time">{{item.createTime}}</span>
					<!-- </a> -->
					<template v-slot:right>
						<view>
							<image @click="deleteFile(item.id)"
								src="../../static/party_building/assets/files/delete.png" class="delete" mode="">
							</image>
						</view>
					</template>
				</uni-swipe-action-item>
			</uni-swipe-action>

		</scroll-view>
	</view>
</template>

<script>
	import {
		d_delete,
		d_download,
		d_upload,
		byFileNameGetInfo
	} from '@/api/api_discipline.js'
	import myHeader from '../components/head.vue'
	export default {
		data() {
			return {
				title: "低效无效专项小组",
				dir_name: '',
				fileName: '',
				file: {},
				imageValue: [],
				history: [0], //栈对象
				id: '', //当前页
				directory: [],
				index: 0, //当前索引
				files: [],
				n: 0,
				height: 500,
				value: '', //shousuo
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				// 当前用户角色
				currentRoleCode: [],
			}
		},
		components: {
			myHead: myHeader,
		},
		watch: {},
		mounted() {
			this.height = uni.getSystemInfoSync().screenHeight * 0.8
			this.getLoginUserRoles()
			this.init()
		},
		methods: {
			onClick(e) {
				console.log(e)
				console.log('点击了' + (e.position === 'left' ? '左侧' : '右侧') + e.content.text + '按钮')
			},
			swipeChange(e, index) {
				console.log(e)
				console.log('当前状态：' + open + '，下标：' + index)
			},
			confirm() {
				let _this = this
				byFileNameGetInfo({
					fileName: this.fileName
				}).then(res => {
					_this.files = res
					_this.directory = []
				})
			},
			bindClick(e) {
				this.history.push(this.index)
				this.index = e
				this.init()
			},
			deleteFile(id) {
				let _this = this
				uni.showModal({
					title: '提示',
					content: '受否确认删除？',
					success: function(res) {
						if (res.confirm) {
							d_delete({
								id: id
							}).then(res => {
								_this.init()
							})
						}
					},
				})
			},
			init() {
				d_download({
					id: this.index
				}).then(res => {
					this.directory = res.lists
					this.files = res.files
				})
			},
			getFile(url) {
				uni.downloadFile({
					url, //仅为示例，并非真实的资源
					success: (res) => {
						console.log(url)
						console.log(url.replace("/api", 'http://192.168.31.140:8081').replace("/downloadFile",
							'/upload'))
						uni.navigateTo({
							url: '../components/file_view/file_view?url=' + url.replace("/api",
								'http://192.168.31.140:8081').replace("/download", '/upload')
						})

					}
				});
			},
			playpapers(url) {
				uni.showModal({
					title: '提示',
					content: '是否确定下载',
					success: function(res) {
						if (res.confirm) {
							let dload = document.createElement("a");
							dload.download = ''; // 设置下载的文件名，默认是'下载'
							dload.href = url;
							document.body.appendChild(dload);
							dload.click();
							dload.remove(); // 下载之后把创建的元素删除
							//   uni.showToast({
							//   title: "正在下载",
							//   icon: "success"
							//   });
						}

					},
				})
			},
			download(url) {
				window.open(url)
				const iframe = document.createElement("iframe");
				iframe.style.display = "none"; // 防止影响页面
				iframe.style.height = 0; // 防止影响页面
				iframe.src = url;
				document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
				// 5分钟之后删除（onload方法对于下载链接不起作用，就先抠脚一下吧）
				setTimeout(() => {
					iframe.remove();
				}, 5 * 60 * 1000);
			},
			saveImg: function(url) {
				var oA = document.createElement("a");
				oA.download = ''; // 设置下载的文件名，默认是'下载'
				oA.href = url;
				document.body.appendChild(oA);
				oA.click();
				oA.remove(); // 下载之后把创建的元素删除
			},
			his_back() {
				if (this.index === 0) {
					this.init()
					return
				}
				this.index = this.history.pop();
				this.init()
			},
			dir_add() {
				if (this.dir_name.length <= 0) {
					uni.showToast({
						title: '请输入名称',
						duration: 2000,
						icon: 'none'
					})
					return
				}
				let _this = this
				d_upload({
					fileName: "",
					path: _this.dir_name,
					pid: _this.index,
					status: 1,
					type: 0,
				}).then(res => {
					_this.dir_namev = '';
					_this.dir_name = ""
					uni.showToast({
						title: '新建成功',
						duration: 2000,
						success() {
							_this.$refs.popup.close()
							_this.dir_namev = '';
							_this.init()
						},
						complete() {}
					})

				})
			},
			select(e) {
				let _this = this
				let source = e.tempFiles[0];
				let token = uni.getStorageSync("AuthToken");
				uni.uploadFile({
					url: '/api/uploadFile', //仅为示例，非真实的接口地址
					filePath: e.tempFilePaths[0],
					name: 'file',
					header: {
						'x-access-token': token
					},
					formData: {
						'name': source.name,
						'size': source.size
					},
					success: (res) => {
						let data = JSON.parse(res.data).data
						console.log(data)
						_this.file = {
							fileName: data.fileName,
							path: data.fileName,
							pid: _this.index,
							status: 0,
							type: 0,
							url: data.url
						}
						_this.$refs.popup1.open('top')
					},
					complete() {
						_this.imageValue = []
					}
				});
			},
			commit_add() {
				let _this = this
				let data = this.file
				d_upload({
					fileName: data.fileName,
					path: data.fileName,
					pid: this.index,
					status: 0,
					type: 0,
					url: data.url
				}).then(res => {
					_this.init()
					_this.$refs.popup1.close()
					
					setTimeout(
						uni.showToast({
							title: '新建成功',
							duration: 2000,
							success() {
								
							},
							complete() {}
						}), 500)
				}).catch(res => {
					uni.showToast({
						title: '新建失败',
						duration: 2000,
						success() {},
						complete() {}
					})
				})
			},
			// 获取登录用户角色
			getLoginUserRoles() {
				// 获取登录用户的id
				let _this = this;
				uni.getStorage({
					key: 'user',
					success(e) {
						let arr = [];
						_this.userId = e.data.user.userId;
						for (let item of e.data.role) {
							if (null != item.roleCode) {
								_this.currentRoleCode.push(item.roleCode)
								if (item.roleCode == 'fl-leader') {
									_this.isLeader = true;
								}
							}
						}
					}
				})
			},
		},
	}
</script>
<style lang="scss" scoped>
	/**
	 * 定义按钮样式
	 */
	@mixin button-commit {
		background: linear-gradient(180deg, #ff5e59, #e20909);
		color: #fff;
	}

	.body {
		/deep/ .uni-popup__wrapper-box {
			background-color: #FFF;
			padding: 10%;
			border-radius: 10px;

			.add {
				@include button-commit;
			}
		}

		/deep/ .uni-navbar {
			.uni-navbar__header-container {

				.uni-easyinput {
					width: 120% !important;
				}
			}

			.uni-navbar__header-btns {
				width: auto !important;

			}

			uni-image {
				width: 70upx !important;
				height: 70upx !important;
				display: inline-block;
				// box-shadow: 1upx 1upx 1upx 1upx  #d4d4d4;
				position: relative;
				top: 20upx;
				margin: 0 5px;
			}
		}

		/deep/ .d_img {
			uni-image {
				width: 70upx;
				height: 70upx;
				margin-left: 2%;
			}

			.front {
				position: absolute;
				top: 15%;
				margin-left: 2%;
				width: 45%;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			.time {
				float: right;
				position: relative;
				top: -50%;
				margin-right: 2%;
			}

			.delete {
				width: 70upx;
				height: 70upx;
				margin-left: 2%;
				background-color: red;
			}
		}
	}
</style>
